<?php
/**
 * 树管理
 * 表字段 id, parent_id，state
 * 
 * 制作:  叶风
 * Qq:    355007778
 * Email: ye.fn@163.com
 *
 */

namespace m;
trait tree_g
{
    
    function getTree($parent_id=0, $loop=-1)
    {
        $res = $this->getLi($parent_id, $loop);
        return dirTree($this->res_parent($res));
    }
    /**
     * 按父列组合
     * 
     */
    function getParent($parent_id=0, $loop=0)
    {
        $res = $this->getLi($parent_id, $loop);
        if ($loop)
            $res = $this->res_parent($res);
        return $res;
    }
    protected function res_parent($res)
    {
        $resP = array();
        foreach ($res as $v)
            $resP[$v['parent_id']][] = $v; 
        
        // switch root
        if ($res && $res[0]['parent_id']!=0)
          {
            $old = $res[0]['parent_id'];
            $resP[0] = $resP[$old];
            unset($resP[$old]);
          }
        return $resP;
    }
    
    /**
     * 列表
     * @param type $parent_ids
     * @param type $loop  -1=无限
     * @param string $where
     * @return type
     */
    function getLi($parent_ids=0, $loop=0, $where='')
	{
        $tables= array('t1'=>array('as'=>$this->table));
		$tables['sub'] = array('as'=>$this->table,'join'=>'LEFT JOIN','on'=>'t1.id=sub.parent_id');
        $where && $where = 'AND '. $where;
		$li = array();
		while ($res = $this->db->group('t1.id')->get($tables, 't1.*, count(sub.id) subNum', "t1.parent_id IN ($parent_ids) $where AND t1.state>0", $this->orderingBy))
		 {
            $parent_ids = '';
			foreach($res as $v)
			 {	 
			   $li[] = $v;
			   $parent_ids .= ','. $v['id'];
			 }
            $parent_ids = substr($parent_ids, 1);
            
			if (!$loop)
				break;
            $loop--;
		 }
		return $li;
	}
    
    /**
     * 所有子类ID，包含本身ID;
     * 
     * @param type $pids
     * @return string
     */
    function ids_sub($pids)
	{
		$ids = $pids;
		do{	
			$idA  = $this->db->getCol($this->table, 'id', "parent_id IN($pids)");
            if (!$idA)
                break;
            
			$pids = implode(',', $idA); 
            $ids .= ','. $pids;
		 }while (TRUE);
         
		return $ids;		
	}
    
    //nav
    function pNav($id, $stopID=0)
    {
        $res = array();
        while ($id){
            if ($stopID==$id)
                break;
            $r = $this->db->getOne($this->table, '*', 'id='. $id);
            $id = $r['parent_id'];
            $res[] = $r;
         }
        krsort($res);
        return $res;
    }
    
	/**
	 * 如果 $pid 为 $id 的父分类返回 True
	 * @param type $id
	 * @param type $pid
	 * @return boolean
	 */
	function is_p($id, $pid)
	{	
		$id = intval($id);
		while ($id)
		  {
            if ($id==$pid)
               return true;         
		  	$id = $this->db->getOneField($this->table, 'parent_id','id='.$id);
		  }
	}
	
    //
    function getOne($id)
    {
        return $this->db->getOne($this->table, '*', 'id='.$id);
    }
	
}
